<?php
namespace app\home\controller;

use app\home\common\Common;
use app\home\common\Page;
use app\home\common\Pagetwo;
use app\infrastructure\uri\Request;
use app\infrastructure\uri\Uri;

/**
 * Created by PhpStorm.
 * User: YD
 * Date: 2017/4/26
 * Time: 16:52
 */
class Coupon extends Common
{
    private $client;
    public  function  __construct(){
        parent::__construct();
        $this->client=new Request();
    }
    public function couponList()
    {
        $p=empty(input('p'))?1:input('p');
        $startIndex=($p-1)*10;
        $countUrl=Uri::HOST.Uri::COUPONLIST;
        $url=Uri::HOST.Uri::COUPONLIST."?limitation=10&offset=".$startIndex;
        $client=new Request();
        $value = $client->getArrayData($url);
        $totalCount =$client->getArrayData($countUrl);
        if($value['code'] != 0){
            $value['data']=[];
        }
        $pager=new Page(count($totalCount['data']),10,$p);
        $page=$pager->show();
        $data=[];
        foreach($value['data'] as $k=>$v){
           $data[]=[
               "id"=>$v['id'],
               "operator_id"=>$v['operator_id'],
               "operator_name"=>$v['operator_name'],
               "name"=>$v['name'],
               "admin_num"=>$v['admin_num'],
               "type"=>$v['type'],
               "bonus"=>$v['bonus'],
               "attachedProductType"=>$v['attachedProductType'],
               "downPeriod"=>$v['downPeriod'],
               "upperPeriod"=>$v['upperPeriod'],
               "downAmount"=>$v['downAmount'],
               "upperAmount"=>$v['upperAmount'],
               "status"=>$v['status'],
               "platFormID"=>$v['platFormID'],
               "use_start_time"=>date("Y-m-d H:i:s",$v['use_start_time']/1000),
               "use_end_time"=>date("Y-m-d H:i:s",$v['use_end_time']/1000),
               "create_time"=>$v['create_time'],
               "update_time"=>$v['update_time']
           ];
        }
        $this->assign('page',$page);
        $this->assign('data',$data);
        $this->assign('totalCount',count($totalCount['data']));
        return view();
    }
    public function couponAdd(){
        if(\think\Request::instance()->isAjax()){
            if(empty($_POST['type'])){
               return ['code'=>2,'msg'=>'0x200','data'=>'please select coupon type'];
            }
            if(empty($_POST['attachedProductType'])){
               return ['code'=>2,'msg'=>'0x200','data'=>'please select attachedProductType'];
            }
            if(empty($_POST['use_start_time'])){
               return ['code'=>2,'msg'=>'0x200','data'=>'please select use_start_time'];
            }
            if(empty($_POST['use_end_time'])){
               return ['code'=>2,'msg'=>'0x200','data'=>'please select use_end_time'];
            }
            if(strtotime($_POST['use_start_time']) >= strtotime($_POST['use_end_time'])){
               return ['code'=>2,'msg'=>'0x200','data'=>'use_start_time can not more than use_start_time'];
            }
            if($_POST['downAmount'] >= $_POST['upperAmount']){
               return ['code'=>2,'msg'=>'0x200','data'=>'downAmount can not more than upperAmount'];
            }
            if($_POST['downPeriod'] >= $_POST['upperPeriod']){
               return ['code'=>2,'msg'=>'0x200','data'=>'downPeriod can not more than upperPeriod'];
            }
            $data=[
                'name'=>$_POST['name'],
                'admin_num'=>$_POST['admin_num'],
                'operator_id'=>session('userid'),
                'operator_name'=>session('username'),
                'type'=>$_POST['type'],
                'attachedProductType'=>$_POST['attachedProductType'],
                'downAmount'=>$_POST['downAmount'],
                'upperAmount'=>$_POST['upperAmount'],
                'upperPeriod'=>$_POST['upperPeriod'],
                'downPeriod'=>$_POST['downPeriod'],
                'use_start_time'=>strtotime($_POST['use_start_time'])*1000,
                'use_end_time'=>strtotime($_POST['use_end_time'])*1000,
                'status'=>$_POST['status'],
                'platFormID'=>$_POST['platFormID']
            ];
            if($_POST['type'] == 1){
                $data['bonus']=$_POST['bonus'];
            }else{
                $data['bonus']=0;
            }
            $url=Uri::HOST.Uri::ADDCOUPON;
            $client=new Request();
            $value = $client->getArrayData($url,$data,3);
            return $value;
        }
        return view();
    }
    public function upStore(){
        if(\think\Request::instance()->isAjax()){
            $data=[
                'status'=>$_POST['status']
            ];
            $id=$_GET['id'];
            $url=Uri::HOST.Uri::UPDATECOUPON."/".$id;
            $client=new Request();
            $value = $client->getArrayData($url,$data,4);
            return $value;
        }
    }
    /**
     * 给用户发放优惠券列表
     */
    public function toUser(){
        $p=empty(input('p'))?1:input('p');
        $startIndex=($p-1)*10;
        $countUrl=Uri::HOST.Uri::COUPONLOG."?user_id=admin";
        $url=Uri::HOST.Uri::COUPONLOG."?user_id=admin&limitation=10&offset=".$startIndex;
        $client=new Request();
        $value = $client->getArrayData($url);
        $totalCount =$client->getArrayData($countUrl);
        if($value['code'] != 0){
            $value['data']=[];
        }
        $pager=new Page(count($totalCount['data']),10,$p);
        $page=$pager->show();
        $this->assign('page',$page);
        foreach($value['data'] as $k=>$v){
            $value['data'][$k]['content']=json_decode($v['content']);
            $value['data'][$k]['create_time']=$v['create_time'];
        }
//        dd($value['data']);
        $this->assign('data',$value['data']);
        $this->assign('totalCount',count($totalCount['data']));
        return view();
    }
    /**
     * 给用户发放优惠券
     */
    public function couponToUser(){
        set_time_limit(0);
        //查询所有有效的优惠券
        $url=Uri::HOST.Uri::COUPONLIST."?status=1";
        $coupon =  $this->client->getArrayData($url);
        if($coupon['code'] == 0){
            $this->assign('coupon',$coupon['data']);
        }
        else{
            $this->assign('coupon',[]);
        }
        if(\think\Request::instance()->isAjax()){
            $query=[];
            if(empty($_POST['coupon'])){
                $aa=[
                    'code'=>4,
                    'msg'=>'请选择要发放的优惠券'
                ];
                return $aa;
            }
            if($_POST['gender'] != 11){
                $query['gender']=$_POST['gender'];
            }
            if(!empty($_POST['upage'])){
                $query['birthday']=[
                    '$gte'=>strtotime($_POST['upage'])
                ];
            }
            if(!empty($_POST['downage'])){
                $query['birthday']=[
                    '$lte'=>strtotime($_POST['downage'])
                ];
            }
            if(!empty($_POST['upage']) && !empty($_POST['downage'])){
                $query['birthday']=[
                    '$gte'=>strtotime($_POST['upage']),
                    '$lte'=>strtotime($_POST['downage'])
                ];
            }
            if(!empty($_POST['upsign'])){
                $query['create_time']=[
                    '$gte'=>$_POST['upsign']
                ];
            }
            if(!empty($_POST['downsign'])){
                $query['create_time']=[
                    '$lte'=>$_POST['downsign']
                ];
            }
            if(!empty($_POST['upsign']) && !empty($_POST['downsign'])){
                $query['create_time']=[
                    '$gte'=>$_POST['upsign'],
                    '$lte'=>$_POST['downsign']
                ];
            }
            $query['limitation']=20000000;
            $url=Uri::HOST.Uri::POSTUSERLIST;
            $value =  $this->client->getArrayData($url,$query,3);
            //查找该优惠券的信息
            $urlone=Uri::HOST.Uri::COUPONLIST."?status=1&id=".$_POST['coupon'];
            $couponOne =  $this->client->getArrayData($urlone);
            $couponOne=$couponOne['data'][0];
            if($value['code'] == 0){
                $totalUser=count($value['data']);
                $client=new Request();
                $toUserCoupon=[];
                $userCouponLog=[];
                foreach($value['data'] as $v){
                    $data=[
                        "coupon_id"=>$_POST['coupon'],
                        "name"=>$couponOne['name'],
                        "operator_id"=>session('userid'),
                        "operator_name"=>session('username'),
                        "coupon_type"=>$couponOne['type'],
                        "attachedProductType"=>$couponOne['attachedProductType'],
                        "status"=>'unused',
                        "downPeriod"=>$couponOne['downPeriod'],
                        "upperPeriod"=>$couponOne['upperPeriod'],
                        "downAmount"=>$couponOne['downAmount'],
                        "upperAmount"=>$couponOne['upperAmount'],
                        "platFormID"=>$couponOne['platFormID'],
                        "expireTime"=>$couponOne['use_end_time'],
                        "useTime"=>'',
                        "phoneNumber"=>$v['userPhone'],
                        "userID"=>$v['id'],
                        "bonus"=>$couponOne['bonus'],
                    ];
                    $toUserCoupon[]=$data;
//                    $coupon = $client->getArrayData($url,$data,3);
                    $couponData=[
                        'type'=>6,
                        'level'=>0,
                        'status'=>0,
                        'user_id'=>$v['id'],
                        'module_id'=>$_POST['coupon'],
                        'module'=>1,
                        'content'=>json_encode([
                            'title'=>'you have a new coupon'
                        ])
                    ];
                    $userCouponLog[]=$couponData;
//                    $aa=$client->getArrayData($couponLogUrl,$couponData,3);
                }
                    //向这些用户发送优惠券
                    $url = Uri::HOST . Uri::INSERTMANYUSERCOUPON;
                    $this->client->getArrayData($url, $toUserCoupon, 3);
                    //记录发放日志
                    $couponLogUrl = Uri::HOST . Uri::INSERTMANYCOUPONLOG;
                    $this->client->getArrayData($couponLogUrl, $userCouponLog, 3);
                    //记录发放日志
                    $couponLogUrl = Uri::HOST . Uri::INSERTCOUPONLOG;
                    $couponData = [
                        'type' => '666',
                        'level' => 0,
                        'status' => 0,
                        'user_id' => 'admin',
                        'module_id' => 'admin',
                        'module' => 666,
                        'content' => json_encode([
                            'title' => 'send conpon to user',
                            'totalUser' => $totalUser,
                            'coupon' => $couponOne,
                            'userInfo' => $value['data']
                        ])
                    ];
                    $aa = $this->client->getArrayData($couponLogUrl, $couponData, 3);
                return ['code'=>0,'msg'=>'发放成功'];
            }else{
                return ['code'=>4,'msg'=>'没有符合该条件的用户'];
            }
        }
        return view();
    }
    public function toUserInfo(){
         $id=$_GET['uid'];
        $countUrl=Uri::HOST.Uri::COUPONLOG."?id=".$id;
        $client=new Request();
        $value = $client->getArrayData($countUrl);
        foreach($value['data'] as $k=>$v){
            $value['data'][$k]['content']=json_decode($v['content']);
            $value['data'][$k]['create_time']=$v['create_time'];
        }
       if(isset($_GET['extend']) && $_GET['extend']==1){
         $colume=[[
             "user_id",
             "user_phone"
         ]
         ];
           $extendData=[];
           foreach($value['data'][0]['content']->userInfo as $k=>$v){
             $extendData[]=[
                 "user_id"=>$v->id,
                 "user_phone"=>$v->userPhone
             ];
           }
           $data = array_merge($colume, $extendData);
           $this->extendToExcel($data);
       }
        $this->assign('data',$value['data'][0]);
            $this->assign('user',$value['data'][0]['content']->userInfo);
        return view();
    }

    /**
     *修改优惠券
     */
    public function editCoupon(){
        if(\think\Request::instance()->isAjax()){
             $editUrl=Uri::HOST.Uri::UPDATECOUPON."/".$_POST['id'];
            $data=[
                "name"=>$_POST['name'],
                "admin_num"=>$_POST['admin_num'],
                "type"=>$_POST['type'],
                "bonus"=>$_POST['bonus'],
                "attachedProductType"=>$_POST['attachedProductType'],
                "downAmount"=>$_POST['downAmount'],
                "upperAmount"=>$_POST['upperAmount'],
                "upperPeriod"=>$_POST['upperPeriod'],
                "downPeriod"=>$_POST['downPeriod'],
                "use_start_time"=>strtotime($_POST['use_start_time'])*1000,
                "use_end_time"=>strtotime($_POST['use_end_time'])*1000,
                "status"=>$_POST['status'],
                "platFormID"=>$_POST['platFormID']
            ];
            $res=$this->client->getArrayData($editUrl,$data,4);
          return $res;
        }
        //查找旧数据
        $id=$_GET['uid'];
        $couponUrl=Uri::HOST.Uri::COUPONLIST."?id=".$id;
        $oldcoupon=$this->client->getArrayData($couponUrl);
        $oldcoupon=$oldcoupon['data'][0];
        $this->assign('data',$oldcoupon);
        return view();
    }
}